import { ref } from 'vue'
import { test } from 'uview-plus';
import { getPrivacyPolicy } from "@/api/login/index"
function useViewModel() {

	const phoneNumberValidator = (rule : any, value : string, callback : Function) => {
		if (value === '') {
			callback(new Error('请输入手机号'));
			return false
		} else if (!test.mobile(value)) {
			callback(new Error('请输入正确的手机号'));
			return false
		} else {
			callback()
			return true
		}
	};
	//表单校验
	const rules = {
		phoneNumber: [
			{
				required: true,
				trigger: ['blur', 'change'],
				validator: phoneNumberValidator
			},
		],
		validCode: [
			{
				required: true,
				message: '请输入验证码',
				trigger: ['blur', 'change'],
			},
		],
	};

	//获取验证码
	const tips = ref('');
	const seconds = ref(60);
	const codeChange = (text) => {
		tips.value = text;
	};
	const end = () => {
	};
	const start = () => {
	};
	//点击"隐私政策"
	let toPrivacy = (code: string) => {
		uni.showLoading()
		getPrivacyPolicy({ code }).then((res) => {
			let data = res.data
			if (data) {
				const file = data.enclosureList[0];
				uni.showLoading()
				uni.downloadFile({
					url: file.url,
					filePath: `${uni.env.USER_DATA_PATH}/${file.name}`,
					success: (res) => {
						const filePath = res.filePath;
						uni.openDocument({
							filePath: filePath,
							showMenu: true,
							success: function (res) {
								// console.log("打开文档成功");
							},
						});
					},
					complete() {
						uni.hideLoading()
					}
				});
			} else {

			}
		}).finally(() => {
			uni.hideLoading()
		})
	}
	
	return {
		seconds,
		start,
		end,
		tips,
		codeChange,
		rules,
		toPrivacy
	}
}

export default useViewModel